<?php
/**
 *
 * @authors Your Name (you@example.org)
 * @date    2018-05-08 14:01:29
 * @version $Id$
 */
/**
 * 游戏操作 用户中心
 * GameCenter/index 显示
 * GameCenter/loginlog  日志
 * GameCenter/payinfo 付费日志
 * GameCenter/logininfo 帐户信息
 * GameCenter/noticeinfo 游戏公告
 * GameCenter/addnotice 游戏公告添加
 * GameCenter/editnotice 游戏公告修改
 * GameCenter/delnotice 游戏公告删去
 * GameCenter/delnotice 游戏公告删去
 * GameCenter/updateinfo 游戏更新信息
 * GameCenter/addupdate 游戏更新添加
 * GameCenter/editupdate 游戏更新修改
 * GameCenter/delupdate 游戏更新删去
 */
namespace app\admin\controller;

use Request;
use think\Validate;

class GameCenter extends Base
{
    private $partitionid; //当前区id
    public function initialize()
    {
        parent::initialize();
        $this->partitionid = session('partitionid'); //别名：避免与控制名冲突
        if (empty($this->partitionid)) {return $this->error('参数错误,请先选择分区，然后再操作', 'Partition/index');}

    }

    public function index()
    {
        $id = $this->request->has('id') ? $this->request->param('id', 0, 'intval') : 0;
        return $this->fetch();
    }

/**
 * 登录日志
 * @return [type] [description]
 */
    public function loginlog($search = '', $val = '', $searchdate = '')
    {

        return $this->showlist($search, $val, $searchdate);
    }

    public function ajaxloginlog($search = '', $searchdate = '', $val = '', $page = 1, $limit = '')
    {

        $where = [];

        $search     = trim($search) ?? '';
        $val        = trim($val) ?? '';
        $limit      = trim($limit) ?? config('webconfig.page');
        $searchdate = trim($searchdate) ?? '';

        if ($searchdate && $searchdate != '-') {
            $searchdate = explode(" - ", $searchdate);
            $where[]    = ['logtime', 'between', [$searchdate[0], $searchdate[1]]];
        }
        // if (!empty($search) && $search == 'username') {
		//	   $info = '';
        //     if (!empty($val)) {
        //         $data = CreateGameModel($this->partitionid, 'game')->table('player')->field('account')->where([['chrname', 'like', '%' . $val . '%']])->select();
        //         foreach ($data as $k => $v) {
        //             $info = $v['account'];
        //         }
        //         //$infos = explode(",", $info);
        //         $where[] = ['uid', 'in', $info];
        //     }
        // } else
        if ($search && $val) {
            if (preg_match("/[\x7f-\xff]/", $val)) {
                $where[] = [$search, 'like', '%' . $val . '%'];
            } else {
                $where[] = [$search, '=', $val];
            }
        }
        $page = $page ?? 1;

        //$data  = $this->ajaxlist($search, $searchdate, $val, $page, $limit);
        //print_r($where);
        $field = '';
        $count = CreateGameModel($this->partitionid, 'user')->table('login_log')->where($where)->count();
        $list  = CreateGameModel($this->partitionid, 'user')->table('login_log')->field($field)->where($where)->page($page, $limit)->order('id', 'desc')->select();

        foreach ($list as $k => $v) {
            $list[$k]['pid'] = \Db::name('platform')->where('num', $v['pid'])->value('name') ?? $v['pid']; //关联渠道名，存在就显示渠道名，不存在显示渠道id
        }
        $list = ["code" => 0, "msg" => "加载中", "count" => $count, "data" => $list];
        return json($list);
        //return $this->ajaxlist($search, $searchdate, $val, 1, $limit, 'tab_consume');

    }

/**
 * 付费日志
 * @return [type] [description]
 */
    public function payinfo($search = '', $val = '', $searchdate = '')
    {
        return $this->showlist($search, $val, $searchdate);
    }

    public function ajaxpayinfo($search = '', $searchdate = '', $val = '', $page = 1, $limit = '')
    {
        /*
        $data  = $this->ajaxlist($search, $searchdate, $val, $page, $limit);
        $field = '';
        $count = CreateGameModel($data['uid'], 'user')->table('pay_info')->where($data['where'])->count();
        $list  = CreateGameModel($data['uid'], 'user')->table('pay_info')->field($field)->where($data['where'])->page($data['page'], $data['limit'])->order('id', 'desc')->select();
        foreach ($list as $k => $v) {
        if ($v['gs'] == 1) {
        $v['gs'] = 'Quick单支付';
        } elseif ($v['gs'] == 2) {
        $v['gs'] = '5884手游支付平台';
        } else {
        $v['gs'] = 'Quick聚合SDK支付';
        }
        $list[$k]['gs'] = $v['gs'];
        }
        $list = ["code" => 0, "msg" => "加载中", "count" => $count, "data" => $list];
        return json($list);
        //return $this->ajaxlist($search, $searchdate, $val, 1, $limit, 'tab_consume');
         *
         */

        $where = [];

        $search     = trim($search) ?? '';
        $val        = trim($val) ?? '';
        $limit      = trim($limit) ?? config('webconfig.page');
        $searchdate = trim($searchdate) ?? '';

        if ($searchdate && $searchdate != '-') {
            $searchdate = explode(" - ", $searchdate);
            $where[]    = ['paytime', 'between', [$searchdate[0], $searchdate[1]]];
        }
        if (!empty($search) && $search == 'username') {
            if (!empty($val)) {
				$info = '';
                $data = CreateGameModel($this->partitionid, 'game')->table('player')->field('seedname')->where([['chrname', 'like', '%' . $val . '%']])->select();
                foreach ($data as $k => $v) {
                    $info = $v['seedname'];
                }
                //$infos = explode(",", $info);
                $where[] = ['chrseed', 'in', $info];
            }
        } else if ($search && $val) {
            if (preg_match("/[\x7f-\xff]/", $val)) {
                $where[] = [$search, 'like', '%' . $val . '%'];
            } else {
                $where[] = [$search, '=', $val];
            }
        }
        $page = $page ?? 1;

        //$data  = $this->ajaxlist($search, $searchdate, $val, $page, $limit);
        //print_r($where);
        $field = '';
        $count = CreateGameModel($this->partitionid, 'user')->table('pay_info')->where($where)->count();
        $list  = CreateGameModel($this->partitionid, 'user')->table('pay_info')->field($field)->where($where)->page($page, $limit)->order('id', 'desc')->select();

        foreach ($list as $k => $v) {
            $list[$k]['username'] = CreateGameModel($this->partitionid, 'game')->table('player')->field('chrname')->where('seedname', $v['chrseed'])->value('chrname');
            if ($v['gs'] == 1) {
                $v['gs'] = 'Quick单支付';
            } elseif ($v['gs'] == 2) {
                $v['gs'] = '5884手游支付平台';
            } else {
                $v['gs'] = 'Quick聚合SDK支付';
            }
            $list[$k]['gs'] = $v['gs'];
        }
        $list = ["code" => 0, "msg" => "加载中", "count" => $count, "data" => $list];
        return json($list);
        //return $this->ajaxlist($search, $searchdate, $val, 1, $limit, 'tab_consume');
    }

/**
 * 帐户信息
 * @return [type] [description]
 */
    public function logininfo($search = '', $val = '', $searchdate = '')
    {
        return $this->showlist($search, $val, $searchdate);
    }

    public function ajaxlogininfo($search = '', $searchdate = '', $val = '', $page = 1, $limit = '')
    {
        $where      = [];
        $search     = trim($search) ?? '';
        $val        = trim($val) ?? '';
        $limit      = trim($limit) ?? config('webconfig.page');
        $searchdate = trim($searchdate) ?? '';

        if ($searchdate && $searchdate != '-') {
            $searchdate = explode(" - ", $searchdate);
            $where[]    = ['logtime', 'between', [$searchdate[0], $searchdate[1]]];
        }
        /*
        if (!empty($search) && $search == 'username1') {
        if (!empty($val)) {
        $data = CreateGameModel($this->partitionid, 'game')->table('player')->field('account')->where([['chrname', 'like', '%' . $val . '%']])->select();
        foreach ($data as $k => $v) {
        $info = $v['account'];
        }
        //$infos = explode(",", $info);
        $where[] = ['userid', 'in', $info];
        }
        } else
         */
        if ($search && $val) {
            if (preg_match("/[\x7f-\xff]/", $val)) {
                $where[] = [$search, 'like', '%' . $val . '%'];
            } else {
                $where[] = [$search, '=', $val];
            }
        }
        $page = !empty($page) ? $page : 1;

        $field = '';
        $count = CreateGameModel($this->partitionid, 'user')->table('login_info')->where($where)->count();
        $list  = CreateGameModel($this->partitionid, 'user')->table('login_info')->field($field)->where($where)->page($page, $limit)->order('id', 'desc')->select();

        foreach ($list as $k => $v) {
            $list[$k]['pid'] = \Db::name('platform')->where('num', $v['pid'])->value('name') ?? $v['pid']; //关联渠道名，存在就显示渠道名，不存在显示渠道id
        }
        $list = ["code" => 0, "msg" => "加载中", "count" => $count, "data" => $list];
        return json($list);
    }

	/**
	 *  游戏公告
	 */
    public function noticeinfo($search = '', $val = '', $searchdate = '')
    {
        return $this->showlist($search, $val, $searchdate);
    }

    public function ajaxnoticeinfo($search = '', $searchdate = '', $val = '', $page = 1, $limit = '')
    {
        $data  = $this->ajaxlist($search, $searchdate, $val, $page, $limit);
        $field = '';
        $count = CreateGameModel($data['uid'], 'user')->table('notice_info')->where($data['where'])->count();
        $list  = CreateGameModel($data['uid'], 'user')->table('notice_info')->field($field)->where($data['where'])->page($data['page'], $data['limit'])->order('id', 'desc')->select();

        $list = ["code" => 0, "msg" => "加载中", "count" => $count, "data" => $list];
        return json($list);
        //return $this->ajaxlist($search, $searchdate, $val, 1, $limit, 'tab_consume');

    }

    /*
    信息添加
     */
    public function addnotice()
    {
        $id = $this->partitionid;
        if (!CreateGameModel($id, 'user')) {
            //增加安全，有点影响性能
            return $this->error('请先正确配置用户数据库信息', 'Partition/index');
        }
        if ($this->request->isPost()) {

            $post   = $this->request->post();
            $id     = Request::post('id/d');
            $result = $this->validate($post, 'app\admin\validate\GameCenter');
            if (true !== $result) {
                return $this->error($result);
            }

            $post = [
                'version'     => Request::post('version'),
                'notice'      => Request::post('notice'),
                'update_time' => date('Y-m-d H:i:s', time()),
            ];
            $data = CreateGameModel($id, 'user')->table('notice_info')->insert($post);
            if (!empty($data)) {
                return $this->success('添加成功', 'admin/GameCenter/noticeinfo');
            }
        }
        $this->assign([
            'id' => $id,
        ]);
        return $this->fetch();
    }

    /*
    信息编辑
     */
    public function editnotice()
    {
        $id  = $this->partitionid;
        $nid = $this->request->has('nid') ? $this->request->param('nid', 0, 'intval') : 0;
        if (!CreateGameModel($id, 'user')) {
            //增加安全，有点影响性能
            return $this->error('请先正确配置用户数据库信息', 'Partition/index');
        }
        if (empty($nid)) {
            return $this->error('参数错误');
        }
        if ($this->request->isPost()) {

            $post = $this->request->post();
            //print_r($post);
            $result = $this->validate($post, 'app\admin\validate\GameCenter');
            if (true !== $result) {
                return $this->error($result);
            }

            $post = [
                'version'     => Request::post('version'),
                'notice'      => Request::post('notice'),
                'update_time' => date('Y-m-d H:i:s', time()),
                'id'          => $nid,
            ];
            $data = CreateGameModel($id, 'user')->table('notice_info')->update($post);

            if ($data) {
                return $this->success('修改成功', 'admin/GameCenter/noticeinfo');
            } else {
                return $this->error('修改失败');
            }
        }
        //$nid = Request::post('nid/d') ? Request::post('nid/d') : "";
        $info = CreateGameModel($id, 'user')->table('notice_info')->find($nid);
        $this->assign([
            'id'   => $id,
            'info' => $info,
            'nid'  => $nid,
        ]);
        return $this->fetch();
    }

    /*
    信息删去
     */
    public function delnotice($value = '')
    {
        $id  = $this->partitionid;
        $nid = $this->request->has('nid') ? $this->request->param('nid', 0, 'intval') : 0;
        if (!$id || !$nid) {return $this->error('参数错误');}

        $data = CreateGameModel($id, 'user')->table('notice_info')->where('id', $nid)->delete();
        if (!empty($data)) {
            return $this->success('删去成功', 'admin/GameCenter/noticeinfo', '', 1);
        }
        return $this->error('删去失败');
    }

/**
 *  游戏更新记录
 */
    public function updateinfo($search = '', $val = '', $id = '', $searchdate = '')
    {
        return $this->showlist($search, $val, $searchdate);
    }

    public function ajaxupdateinfo($search = '', $searchdate = '', $val = '', $page = 1, $limit = '')
    {
        $data  = $this->ajaxlist($search, $searchdate, $val, $page, $limit);
        $field = '';
        $count = CreateGameModel($data['uid'], 'user')->table('update_info')->where($data['where'])->count();
        $list  = CreateGameModel($data['uid'], 'user')->table('update_info')->field($field)->where($data['where'])->page($data['page'], $data['limit'])->order('id', 'desc')->select();

        $list = ["code" => 0, "msg" => "加载中", "count" => $count, "data" => $list];
        return json($list);
        //return $this->ajaxlist($search, $searchdate, $val, 1, $limit, 'tab_consume');

    }

    /*
    信息添加
     */
    public function addupdate()
    {
        $id = $this->partitionid;
        if (!CreateGameModel($id, 'user')) {
            //增加安全，有点影响性能
            return $this->error('请先正确配置用户数据库信息', 'Partition/index');
        }
        if ($this->request->isPost()) {

            $post = $this->request->post();
            $id   = Request::post('id/d');

            $validate = Validate::make([
                'version'    => 'require|max:11',
                'update_url' => 'require|url',
            ]);

            $post = [
                'type'        => Request::post('type'),
                'os'          => Request::post('os'),
                'version'     => Request::post('version'),
                'update_url'  => Request::post('update_url'),
                'update_time' => date('Y-m-d H:i:s', time()),
            ];

            if (!$validate->check($post)) {
                return $validate->getError();
            }

            $data = CreateGameModel($id, 'user')->table('update_info')->insert($post);
            if (!empty($data)) {
                return $this->success('添加成功', 'admin/GameCenter/updateinfo');
            }
        }
        $this->assign([
            'id' => $id,
        ]);
        return $this->fetch();
    }

    /*
    信息编辑
     */
    public function editupdate()
    {
        $id  = $this->partitionid;
        $nid = $this->request->has('nid') ? $this->request->param('nid', 0, 'intval') : 0;
        if (!CreateGameModel($id, 'user')) {
            //增加安全，有点影响性能
            return $this->error('请先正确配置用户数据库信息', 'Partition/index');
        }
        if (empty($nid)) {
            return $this->error('参数错误');
        }
        if ($this->request->isPost()) {

            $post = $this->request->post();

            $validate = Validate::make([
                'version'    => 'require|max:11',
                'update_url' => 'require|url',
            ]);

            $post = [
                'type'        => Request::post('type'),
                'os'          => Request::post('os'),
                'version'     => Request::post('version'),
                'update_url'  => Request::post('update_url'),
                'update_time' => date('Y-m-d H:i:s', time()),
                'id'          => $nid,
            ];

            if (!$validate->check($post)) {
                return $validate->getError();
            }
            $data = CreateGameModel($id, 'user')->table('update_info')->update($post);

            if ($data) {
                return $this->success('修改成功', 'admin/GameCenter/updateinfo');
            } else {
                return $this->error('修改失败');
            }
        }
        //$nid = Request::post('nid/d') ? Request::post('nid/d') : "";
        $info = CreateGameModel($id, 'user')->table('update_info')->find($nid);
        //print_r($info);
        $this->assign([
            'id'   => $id,
            'info' => $info,
            'nid'  => $nid,
        ]);
        return $this->fetch();
    }

    /*
    信息删去
     */
    public function delupdate($value = '')
    {
        $id  = $this->partitionid;
        $nid = $this->request->has('nid') ? $this->request->param('nid', 0, 'intval') : 0;
        if (!$id || !$nid) {return $this->error('参数错误');}
        $data = CreateGameModel($id, 'user')->table('update_info')->where('id', $nid)->delete();
        if (!empty($data)) {
            return $this->success('删去成功', 'admin/GameCenter/updateinfo', '', 1);
        }
        //return $this->error('删去失败');
    }

/**
 * 基础数据
 * @param  string $search     [description]
 * @param  string $val        [description]
 * @param  string $id         [description]
 * @param  string $searchdate [description]
 * @return [type]             [description]
 */
    private function showlist($search = '', $val = '', $searchdate = '', $array = [])
    {
        $id = $this->partitionid;
        if (!CreateGameModel($id, 'user')) {
            //增加安全，有点影响性能
            return $this->error('请先正确配置用户数据库信息', 'Partition/index');
        }
        $search     = trim($search) ?? '';
        $val        = trim($val) ?? '';
        $searchdate = trim($searchdate) ?? '';
        //echo $searchdate;
        $this->assign([
            'id'         => $id,
            'search'     => $search,
            'val'        => $val,
            'searchdate' => $searchdate,
            'array'      => $array,
        ]);
        return $this->fetch();
    }

    private function ajaxlist($search = '', $searchdate = '', $val = '', $page = 1, $limit = '')
    {
        $id = $this->partitionid;
        if (empty($id)) {return $this->error('参数错误');}
        if (!CreateGameModel($id, 'user')) {
            //增加安全，有点影响性能
            return $this->error('请先正确配置用户数据库信息', 'Partition/index');
        }
        $where = [];

        $search     = trim($search) ?? '';
        $val        = trim($val) ?? '';
        $limit      = trim($limit) ?? config('webconfig.page');
        $searchdate = trim($searchdate) ?? '';

        if ($searchdate && $searchdate != '-') {
            $searchdate = explode(" - ", $searchdate);
            $where[]    = ['logtime', 'between', [$searchdate[0], $searchdate[1]]];
        }
        if ($search && $val) {
            if (preg_match("/[\x7f-\xff]/", $val)) {
                $where[] = [$search, 'like', '%' . $val . '%'];
            } else {
                $where[] = [$search, '=', $val];
            }
        }
        $page = $page ?? 1;

        return [
            'uid'   => $id,
            'where' => $where,
            'page'  => $page,
            'limit' => $limit,
        ];
    }

}
